

<template>
  <div>

    <!-- table 组件-->
    <dyn-table
            :queryParams="query"
            :listBtnObj="dynTableData.listBtnObj"
            :listTable="dynTableData.listTable"
            :eventName="eventName"
            ref="dynTableBox"
    />
    <!-- 查看表单 -->
    <purchaseContract-show ref="purchaseContractShow"/>
    <!-- 新建表单 -->
    <purchaseContract-add ref="purchaseContractAdd"  @created="doQueryList({ page: 1 })"/>
    <!-- 编辑表单 -->
    <purchaseContract-edit ref="purchaseContractEdit"  @updated="doQueryList({})"/>
    <!-- 详情表单 -->
    <Tabs ref="tabs" :params="params" @doQueryList="doQueryList({})"/>
    <!-- 撤销表单 -->
    <purchaseContract-undo ref="purchaseContractUndo" @undo="doQueryList({})"/>

  </div>
</template>

<script>
import purchaseContractAdd from './add'
import purchaseContractEdit from './edit'
import purchaseContractShow from './show'
import Tabs from '@/components/Tabs/index'
import purchaseContractUndo from './undo'
import defaultSettings from '@/settings'
import { getAccessToken } from '@/utils/auth'

import { getOffsetTop, queryToString } from '@/utils/public'
import purchaseContractApi from '@/api/platformLiyonghui/purchaseContract'
import principalPartApi from '@/api/platformLiyonghui/principalPart'

import elDragDialog from '@/directive/el-drag-dialog'
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination'
import DynTable from '@/components/DynTable'
import specialAttr from '@/utils/special-attr'
import tableConfigApi from '@/api/platformLiyonghui/tableConfig'
import dynTableApi from '@/api/platformLiyonghui/dynTable'



export default {
  name: 'PurchaseContractTable',
  directives: { elDragDialog },
  components: {
    DynTable,
    Pagination,
    purchaseContractAdd,
    purchaseContractEdit,
    purchaseContractShow,
    purchaseContractUndo,
    Tabs
  },
  data() {
    return {
        // 组件内部调用的查询和重置方法
      eventName: {
        search: 'handleQuery',
        reset: 'handleReset',
        drags: 'handleDrags',//拖拽区确定按钮
        order: 'sortChange',
        page: 'handlePage'
      },
      // 动态表格属性
      dynTableData: {
        listBtnObj: [],
        listTable: {},
        inLineBtnList: []
      },
      params: {
        'businessKey': '9a9c4467364d45fa85cd7633df377923',
        'variable-name': 'workflowPrefix_form'
      },
      listQuery: {},
      tableHeight: -1,
      userId: '',
      remoteCallPayload: {
        url: '',
        token: '',
        method: 'post',
        state: 0
      },
      options: {
        principalPart: [],
      },
      query: {
        pageNum: 1,
        pageSize: 20,
        sortBy: 'id',
        sortOrder: 'desc',
        q: ''
      },
    }
  },
  created() {
    Promise.all([
        this.getPrincipalPartApi(),
    ]).then(() =>{
    
      const objDatas = [];
      const code = sessionStorage.getItem('routerCode');
      const menus = JSON.parse(sessionStorage.getItem('routerMenus'));
      console.log(code)
      console.log(menus)
      if(menus!=null){
        menus.forEach((item) => {
          if(item.menuCode==code){
            objDatas.push(item)
          }
        })
      }
      const objData = objDatas[0]
      this.genDynTable(objData);
    })
  },
  mounted() {
    this.userId = this.$store.getters.userId
  },
  computed: {
    ...mapGetters([
      'dictList',
      'dynamicList'
    ])
  },
  methods: {
  btnFun(obj){
      if(this.dynTableData.inLineBtnList && this.dynTableData.inLineBtnList.length > 0){
        const arrayList = JSON.parse(JSON.stringify(this.dynTableData.inLineBtnList))

        if (obj.workflowState === '1') {
            // 草稿
          this.dynTableData.inLineBtnList.forEach((item,index)=>{
           
            if (item.code == 'CONTRACT_0002_undo') {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_rushDo") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_work_details") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_submit") {
              arrayList[index].isShow = true
            }
           })
        }
        else if (obj.workflowState === '2') {
        // 驳回
          this.dynTableData.inLineBtnList.forEach((item,index)=>{
           
            if (item.code == "CONTRACT_0002_undo") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_rushDo") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_work_details") {
              arrayList[index].isShow = true
            }
            if (item.code == "CONTRACT_0002_submit") {
              arrayList[index].isShow = true
            }
           })
        }
        else if (obj.workflowState === '3') {
             // 提交
          this.dynTableData.inLineBtnList.forEach((item,index)=>{
           
            if (item.code == "CONTRACT_0002_undo") {
              arrayList[index].isShow = true
            }
            if (item.code == "CONTRACT_0002_rushDo") {
              arrayList[index].isShow = true
            }
            if (item.code == "CONTRACT_0002_work_details") {
              arrayList[index].isShow = true
            }
            if (item.code == "CONTRACT_0002_submit") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_delete") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_update") {
              arrayList[index].isShow = false
            }
           })
        }
        else if (obj.workflowState === '4') {
            // 通过
          this.dynTableData.inLineBtnList.forEach((item,index)=>{
            if (item.code == "CONTRACT_0002_undo") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_rushDo") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_work_details") {
              arrayList[index].isShow = true
            }
            if (item.code == "CONTRACT_0002_submit") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_delete") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_update") {
              arrayList[index].isShow = false
            }
           })
        }
        else if (obj.workflowState === '5') {
 // 未通过
          this.dynTableData.inLineBtnList.forEach((item,index)=>{
            if (item.code == "CONTRACT_0002_undo") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_rushDo") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_work_details") {
              arrayList[index].isShow = true
            }
            if (item.code == "CONTRACT_0002_submit") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_delete") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_update") {
              arrayList[index].isShow = false
            }
           })
        }
        else if (obj.workflowState === '6') {
           this.dynTableData.inLineBtnList.forEach((item,index)=>{
            if (item.code == "CONTRACT_0002_undo") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_rushDo") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_work_details") {
              arrayList[index].isShow = true
            }
            if (item.code == "CONTRACT_0002_submit") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_delete") {
              arrayList[index].isShow = false
            }
            if (item.code == "CONTRACT_0002_update") {
              arrayList[index].isShow = false
            }
           })
        }
          return arrayList

      }
      return [];
    },



    getPrincipalPartApi () {
      return new Promise((resolve,reject)=>{
        principalPartApi.findOptions({sortBy: 'id',sortOrder: 'desc',q: '',}).then(res => {
        this.options.principalPart = res.data.map(entity => ({label: entity.name, value: entity.id}))
          resolve()
        })
      })
      },
     
    // 组装数据
    genDynTable(objData){
      this.dynTableData.listBtnObj = objData.listBtnObj
      this.dynTableData.listTable = objData.listTable
      //获取字典项
      const dictionaryEntry = JSON.parse(sessionStorage.getItem('constCode'))
      objData.listTable.tableHeader.forEach(headerField => {
        // 组装枚举数据
        if(headerField.fieldSpecialType === specialAttr.fieldSpecialType.ENUM_TYPE.code){
          console.log('ENUM_TYPE',headerField.dicTypeData)
          if(headerField.filtered){
            // headerField.filterQuery.options = this.$store.getters.dictList[headerField.dicTypeData].map(item => ({ label: item.name, value: item.value}))
            headerField.filterQuery.options = []
            dictionaryEntry.forEach((item) => {
              if(item.constCode == headerField.dicTypeData){
                headerField.filterQuery.options.push({ label: item.name, value: item.value })
              }
            })
            console.log('headerField.filterQuery.options',headerField.filterQuery.options)
          }
          // 方法名称
          headerField.webFilter = 'findEnumLabel'
          // 数组名称
          // headerField.webFilterArr = this.$store.getters.dictList[headerField.dicTypeData].map(item => ({ label: item.name, value: item.value}))
          headerField.webFilterArr = []
          dictionaryEntry.forEach((item) => {
            if(item.constCode == headerField.dicTypeData){
              headerField.webFilterArr.push({ label: item.name, value: item.value })
            }
          })
          // 属性名称(枚举不需要属性名称)
          headerField.webFilterProp = 'label'
          headerField.webFilterValue = 'value'
        // 组装外键数据
        }else if(headerField.fieldSpecialType === specialAttr.fieldSpecialType.FK_TYPE.code){
          console.log('FK_TYPE')
          if(headerField.filtered){
            headerField.filterQuery.options = this.options[headerField.foreignData]
          }
          // 方法名称
          headerField.webFilter = 'findForeignKey'
          // 数组名称
          headerField.webFilterArr = this.options[headerField.foreignData]
          // 属性名称
          headerField.webFilterProp = 'label'
          //对比值
          headerField.webFilterValue = 'value'
          if (headerField.editType === 'tree_select') {
          headerField.webFilterValue = 'id'
          }
        // 组装多对多实体数据
        }else if(headerField.fieldSpecialType === specialAttr.fieldSpecialType.MTM_TYPE.code){
          if(headerField.filtered){
              headerField.filterQuery.options = this[headerField.webEntityData]
          }
        // 组装其他数据
        }else if(headerField.fieldSpecialType === specialAttr.fieldSpecialType.OTHER_WEB.code){
          console.log('OTHER_WEB')
          if(headerField.filtered){
            headerField.filterQuery.options = this[headerField.webEntityData]
          }
        }
        if(headerField.column == "workflowState"){
          // 方法名称
          headerField.webFilter = 'findEnumLabel'
          // 数组名称
          // headerField.webFilterArr = this.$store.getters.dictList[headerField.dicTypeData].map(item => ({ label: item.name, value: item.value}))
          headerField.webFilterArr = [
            { label: '执行中', value: 0 },
            { label: '草稿', value: 1 },
            { label: '驳回', value: 2 },
            { label: '提交', value: 3 },
            { label: '通过', value: 4 },
            { label: '不通过', value: 5 },
            { label: '完成', value: 6 },
          ]
          // 属性名称(枚举不需要属性名称)
          headerField.webFilterProp = 'label'
          headerField.webFilterValue = 'value'
        }
      })
      // 获取行内按钮集合
      objData.listBtnObj.forEach(item=> {
          if(item.isLine === true){
              item.isShow = true
              this.dynTableData.inLineBtnList.push(item)
          }
      })

      this.doQueryList({ page: 1 })
    },
    /**
     * 触发后端排序
     */
    sortChange({ name, order }) {
      this.$set(this.query,'sortBy',name)
      if (order === 'ascending') {
        this.$set(this.query,'sortOrder','asc')
      } else {
        this.$set(this.query,'sortOrder','desc')
      }
      this.doQueryList({ page: 1 })
    },
    /**
     * 触发搜索操作
     */
    handleQuery(queryVariable) {
      this.$set(this.query,'q',queryToString(queryVariable))
      this.doQueryList({ page: 1 })
    },
    //拖拽区确定按钮
    handleDrags(tableHeaders){
      const dynTableHeader = []
      tableHeaders.forEach(item => {
        const header = {
          column: item.column,
          showed: item.showed,
          fixed: item.fixed,
          filtered: item.filtered
        }
        dynTableHeader.push(header)
      })
      const {tenantId, groupId, orgId, userId, account} = JSON.parse(sessionStorage.getItem('userinfos')) || {};
      const customTableColumn = {
        id: null,
        menuCode: sessionStorage.getItem('routerCode'),
        tenantId: tenantId,
        groupId: groupId,
        orgId: orgId,
        userId: userId,
        account: account,
        dynTableHeader: dynTableHeader
      }
      tableConfigApi.saveCustomTableColumn(customTableColumn).then(res => {
        if (res.code === '000000') {
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.dynTableData.listTable.tableHeader = JSON.parse(JSON.stringify(tableHeaders))
          this.$nextTick(()=>{
            this.$refs.dynTableBox.doLayoutTable()
          })
          // 刷新动态表单表格
          dynTableApi.getDynTable(tenantId).then(res => {
            sessionStorage.setItem("routerMenus", JSON.stringify(res.data));
          }).catch(err => {
            console.log(err)
          })
          this.doQueryList({ page: 1 })
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    // 重置按钮方法
    handleReset() {
      this.query = {
        pageNum: 1,
        pageSize: 20,
        sortBy: 'id',
        sortOrder: 'desc',
        q: ''
      }
      this.doQueryList({ page: 1 })
    },
    //分页
    handlePage(param){
      this.doQueryList({ page: param.pageNum, limit: param.pageSize })
    },
    /**
     * 执行列表查询
     */
    doQueryList({ page, limit }) {
      if (page) {
        this.query.pageNum = page
      }
      if (limit) {
        this.query.pageSize = limit
      }
      this.listLoading = true

      const args = Object.assign({}, this.query)
      this.listLoading = true
      return purchaseContractApi.finds(args)
        .then(res => {
          res.data.list.forEach(item=>{
            item.operation = JSON.parse(JSON.stringify(this.dynTableData.inLineBtnList))
            item.operation.forEach(op =>{
              if (op.isStarted) {
                let {label, labelFalse} = op;
                if (!item[op.code]) {
                  op.label = labelFalse;
                }
                item[op.code] = item[op.code] ? labelFalse : label
              }
            })
            item.operation = this.btnFun(item)
          })
          this.$set(this.dynTableData.listTable,'total',res.data.total)
          this.$set(this.dynTableData.listTable,'tableData',res.data.list)
        })
    },

    /**
     * 删除单条记录
     */
    handleDeleteSingle(row) {
      return this.$common.confirm('是否确认删除')
        .then(() => {
          this.listLoading = true
          purchaseContractApi.del(row.id)
          .then(() => {
                this.$common.showMsg('success', '删除成功')
                return this.doQueryList({ page: 1 })
          })
        })
        .catch(() => {
          this.$message({type: 'info',message: '已取消删除'})
        })
    },
    /**
     * 批量删除记录
     */
    handleDeleteBatch(listRow) {
      if (listRow.length <= 0) {
        this.$common.showMsg('warning', '请选择采购合同')
        return
      }
      return this.$common.confirm('是否确认删除')
        .then(() =>{
            this.listLoading = true
            purchaseContractApi.deleteBatch(listRow.map(row => row.id))
            .then(() => {
                this.$common.showMsg('success', '删除成功')
                return this.doQueryList({ page: 1 })
            }).catch(()=>{
                this.listLoading = false
            })
        }).catch(() => {
              this.$message({
              type: 'info',
              message: '已取消删除'
          })
        })
    },


    /**
     * 打开新建表单
     */
    handleCreate() {
      this.$refs.purchaseContractAdd.handleCreate()
    },
    /**
     * 打开查看表单
     */
    handleShow(row) {
      this.$refs.purchaseContractShow.handleShow(row)
    },
    /**
     * 打开编辑表单
     */
    handleUpdate(row) {
      this.$refs.purchaseContractEdit.handleUpdate(row)
    },
    /**
     * 根据数据状态按钮是否隐藏
     */
    isAttrHide(row,attr) {
      return row.hiddenAttrs.includes(attr)
    },
    /**
     * 获取数据状态特性
     */
    getFieldFeature(row){
      //草稿
      if(row.workflowState === '1'){
        //'详情','编辑','删除','提交'
        row.hiddenAttrs =  ['details','edit','delete','submit']
      //已驳回
      }else if(row.workflowState === '2'){
        //'详情','编辑','删除','提交'
        row.hiddenAttrs =  ['details','edit','delete','submit']
      //已提交
      }else if(row.workflowState === '3'){
        //'详情','撤销','催办'
        row.hiddenAttrs =  ['details','undo','rushDo']
      //已通过
      }else if(row.workflowState === '4'){
        //'详情','存档'
        row.hiddenAttrs =  ['details','archive']
      //未通过
      }else if(row.workflowState === '5'){
        //'详情','存档'
        row.hiddenAttrs =  ['details','archive']
      }else{
        row.hiddenAttrs = []
      }

    },
    /**
     * 提交
     */
    handleSubmit(row) {
      this.$common.confirm('是否确认提交')
        .then(()=>{
          this.listLoading = true
          //移除 hiddenAttrs   （不移除临时使用的 hiddenAttrs的话,与后台接收的json对象对应不上喽，导致后台接收参数为null）
          let form = Object.assign({},row)
          this.remoteCallPayload.url = 'http://' + defaultSettings.gateway + '/liyonghui/purchaseContract/updateByWorkflow'
          this.remoteCallPayload.token = 'Bearer ' + getAccessToken()

          form.remoteCallPayload = this.remoteCallPayload
          delete form.hiddenAttrs
          //调用提交接口
          purchaseContractApi.submit(form).then(res=>{
            //未找到流程实例
            if('000000' === res.code){
                this.doQueryList({ page: 1 });
                this.$message({
                  type: 'success',
                  message: '提交成功！'
                })
            }else if('222222' === res.code){
              this.$message({
                type: 'warn',
                message: '未找到流程实例'
              })
              //结束业务状态
              //this.handEndProcess(form)
              //this.listLoading = false
            }else if('500' === res.code){
              this.$message({
                type: 'error',
                message: '系统异常,联系管理员！'
              })
              this.listLoading = false
            }
          }).catch(()=>{
              this.listLoading = false
          })
        })
    },
    /**
     * 详情
     * @param row
     */
    handleDetails(row) {
      delete row.hiddenAttrs

      const params = {
        'businessKey': '9a9c4467364d45fa85cd7633df377923' + row.id,
        'variable-name': 'workflowPrefix_form'
      }

      this.$refs['tabs'].showFn(row, params, this.dynTableData.listTable.tableHeader)
    },
    /**
     * 撤销
     */
    handleUndo(row) {
      this.$refs.purchaseContractUndo.handleCreate(this.params.businessKey + row.id)
    },
    /**
     * 结束业务
     *
     * 未找到流程实例，是否结束业务
     * @param row
     */
    handEndProcess(row) {
      this.$common.confirm('未找到流程实例,是否结束业务')
        .then(()=>{
          this.listLoading = true
          purchaseContractApi.endProcess(row).then(res=>{
            if(res.code === '000000'){
              this.doQueryList({ page: 1 });
              this.$message({
                type: 'success',
                message: '结束成功!'
              })
              this.listLoading = false
            }else{
              this.$message({
                type: 'error',
                message: '结束状态失败!'
              })
              this.listLoading = false
            }
          })
      })
    },
    /**
     * 催办
     * @param row 业务对象
     */
    handleRushDo(row) {
      this.$common.confirm('是否催办')
        .then(()=>{
          this.listLoading = true
          purchaseContractApi.rushDo(this.params.businessKey + row.id).then(res=>{
            if(res.code === '000000'){
              this.$message({
                type: 'success',
                message: '催办成功!'
              })
              this.listLoading = false
            }else{
              this.$message({
                type: 'error',
                message: '催办失败!'
              })
              this.listLoading = false
            }
          })
        })
    },
    checkboxT(row, index) {
     if (!(row.workflowState === '1')) {
        return 0
      } else {
        return 1
      }
    },
    exportExcel() {
      this.export()
    },
    exportAllExcel() {
      this.listLoading = true
      const args = Object.assign({}, this.query)
      args.total = this.dynTableData.listTable.total
      purchaseContractApi.exportExcelAll(args).then(res=>{
        this.listLoading = false
        let link = document.createElement('a');
        let body = document.querySelector('body');
        link.href = window.URL.createObjectURL(res);
        link.download = "记录.xlsx";
        // fix Firefox
        link.style.display = 'none';
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      })
    },
    export(pageNum) {
      this.listLoading = true
      const args = Object.assign({}, this.query)
      if (pageNum) {
        args.pageNum = pageNum
      }
      purchaseContractApi.exportExcel(args).then(res=>{
        this.listLoading = false
        let link = document.createElement('a');
        let body = document.querySelector('body');
        link.href = window.URL.createObjectURL(res);
        link.download = "记录（第" + args.pageNum + "页）.xlsx";
        // fix Firefox
        link.style.display = 'none';
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      })
    },
    importExcel(excelFile){
      this.listLoading = true
        purchaseContractApi.importExcel(excelFile).then(res=>{
          if (res.code === '000000') {
            this.$message({
              type: 'success',
              message: '导入成功!'
            })
            this.doQueryList({ page: 1 })
          }else{
            this.$message({
              type: 'error',
              message: res.message
            })
            this.listLoading = false
          }
        }).catch(()=>{
          this.listLoading = false
        })
      }
  }
}
</script>
